package cn.csc.module.distribute.controller.app.weixin;

import cn.csc.framework.common.enums.UserTypeEnum;
import cn.csc.framework.common.pojo.CommonResult;
import cn.csc.module.distribute.controller.app.weixin.vo.WxaCodeUnlimitReqVO;
import cn.csc.module.distribute.convert.wx.WeixinConvert;
import cn.csc.module.system.api.social.SocialClientApi;
import cn.csc.module.system.api.social.dto.SocialWxaCodeUnlimitReqDTO;
import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

import java.io.ByteArrayInputStream;
import java.io.File;

import static cn.csc.framework.common.pojo.CommonResult.success;

/**
 * @author liuchuang
 * @version 1.0
 * @modify
 * @since 2025/4/21 11:27
 */
@Tag(name = "微信小程序")
@RestController
@RequestMapping("/distribute/wx-ma")
@Validated
@Slf4j
public class AppWxMaController {

    @Resource
    private SocialClientApi socialClientApi;

    @Value("${csc.file.tmp}")
    private String tmpPath;

    @PostMapping("/create-qrcode-unlimit-bytes")
    @Operation(summary = "创建永久微信二维码",
            description = "参考 https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/qr-code/getUnlimitedQRCode.html 文档")
    public CommonResult<byte[]> createQrcodeBytes(@RequestBody WxaCodeUnlimitReqVO reqVO) {
        SocialWxaCodeUnlimitReqDTO reqDTO = WeixinConvert.INSTANCE.convert(reqVO);
        reqDTO.setUserType(UserTypeEnum.MEMBER.getValue());
        byte[] data = socialClientApi.getWxaCodeUnlimitBytes(reqDTO).getCheckedData();
        File file = FileUtil.writeBytes(data, tmpPath + IdUtil.fastSimpleUUID() +"." + FileTypeUtil.getType(new ByteArrayInputStream(data)));
        log.info("file : {} , {}",file.getName(), FileTypeUtil.getType(file));
        return success(data);
    }



}
